package com.example.administrator.u17.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.administrator.u17.R;
import com.example.administrator.u17.model.GameDetail;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class GameDetailActivity extends AppCompatActivity {

    private int appId;

    private ArrayList<GameDetail.DataBean.ReturnDataBean> mList;
    private ImageView iv1,iv2;
    private TextView tvTitle,tvDownTimes,tvNeiCun,tvType,tvDesrcibe;
    private String path;
    private Button btnDownLoad;
    private ImageView ivGameDetailBack;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_game_detail);
        initView();
        initData();
    }

    private void initData() {
        loadData();
    }

    private void initView() {
        mList=new ArrayList<>();
        iv1= (ImageView) findViewById(R.id.iv_mine_game_detail);
        iv2= (ImageView) findViewById(R.id.iv_game_detail);
        tvTitle= (TextView) findViewById(R.id.tv_mine_game_title_detail);
        tvDesrcibe= (TextView) findViewById(R.id.tv_game_detail_describle);
        tvDownTimes= (TextView) findViewById(R.id.tv_mine_game_comment_detail);
        tvNeiCun= (TextView) findViewById(R.id.tv_mine_game_NeiCun_detail);
        tvType= (TextView) findViewById(R.id.tv_mine_game_cosPlay_detail);
        btnDownLoad= (Button) findViewById(R.id.btn_mine_game_downLoad);
        ivGameDetailBack= (ImageView) findViewById(R.id.iv_game_detail_back);
        ivGameDetailBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    public void loadData(){
        path="http://game.u17.com/game/mobile/appDetails/"+getAppId()+"?v=3220102&key=8d5cdd4dcec75f94a41f69f5658e7fa225b37ead9c932da7c988bfa6b8a59502f67cb41dbfed8353da3741ad7d569b7bb7943237143c7c3220f07cd9c69d72e6b4ae2da174eda3876cf9bb741848d4a12846343c6ae420908ef3e27c51dc349e3a2c489c97bdc512%253A%253A%253Au17&model=8676-M01&come_from=openqq&android_id=d893eaa960d8a5e6";
        x.http().get(new RequestParams(path), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                GameDetail detail=new Gson().fromJson(s,GameDetail.class);
                mList.add(detail.getData().getReturnData());
                Picasso.with(GameDetailActivity.this).load(mList.get(0).getApp().getCoverUrl())
                        .into(iv1);
                Picasso.with(GameDetailActivity.this).load(mList.get(0).getApp().getSmallPictureUrls().get(0))
                        .into(iv2);
                tvTitle.setText(detail.getData().getReturnData().getApp().getTitle());
                tvType.setText(detail.getData().getReturnData().getApp().getGameType());
                tvNeiCun.setText(detail.getData().getReturnData().getApp().getSize()/1024+"MB");
                tvDesrcibe.setText(detail.getData().getReturnData().getApp().getDesc());
                tvDownTimes.setText(detail.getData().getReturnData().getApp().getDownloadTimes()+"次下载");
                btnDownLoad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String DownPath=mList.get(0).getApp().getDownUrl();
                        downLoadFile(DownPath);
                        openFile(new File(DownPath));
                    }
                });
            }


            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    public int getAppId() {
        Intent intent=getIntent();;
        if (intent!=null){
            appId=intent.getIntExtra("appId",0);
        }
        return appId;
    }

    protected File downLoadFile(String httpUrl) {
        // TODO Auto-generated method stub
        final String fileName = "updata.apk";
        File tmpFile = new File("/sdcard/update");
        if (!tmpFile.exists()) {
            tmpFile.mkdir();
        }
        final File file = new File("/sdcard/update/" + fileName);

        try {
            URL url = new URL(httpUrl);
            try {
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                InputStream is = conn.getInputStream();
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buf = new byte[256];
                conn.connect();
                double count = 0;
                if (conn.getResponseCode() >= 400) {
                    Toast.makeText(GameDetailActivity.this, "连接超时", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    while (count <= 100) {
                        if (is != null) {
                            int numRead = is.read(buf);
                            if (numRead <= 0) {
                                break;
                            } else {
                                fos.write(buf, 0, numRead);
                            }

                        } else {
                            break;
                        }

                    }
                }

                conn.disconnect();
                fos.close();
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }

        return file;
    }
//打开APK程序代码

    private void openFile(File file) {
        // TODO Auto-generated method stub
        Log.e("OpenFile", file.getName());
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

}
